﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Client.Models;

namespace Client.ViewModel
{
    public class SetUpViewModel: ICommandNotify.NotifyBase
    {
        public SetUpViewModel()
        {
            SetUpCommand = new ICommandNotify.Command(SetUpDoExecute, SetUpCanExecute);
            AddCommand = new ICommandNotify.Command(AddDoExecute, AddCanExecute);
            DeleteCommand = new ICommandNotify.Command(DeleteExecute, DeleteExecute);
            RowClickCommand = new ICommandNotify.Command(OnRowClick, CanRowClick);
        }


        #region 命令
        public ICommandNotify.Command RowClickCommand { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public ICommandNotify.Command SetUpCommand { get; set; }
        /// <summary>
        /// 添加配置文件
        /// </summary>
        public ICommandNotify.Command AddCommand { get; set; }
        /// <summary>
        /// 删除配置文件
        /// </summary>
        public ICommandNotify.Command DeleteCommand { get; set; }
        #endregion
        #region 方法
        private bool CanRowClick()
        {
            return true;
        }

        private void OnRowClick(object obj)
        {

        }
        private bool SetUpCanExecute()
        {
            return true;
        }
        private void SetUpDoExecute(object obj)
        {         
            SetUpType = Convert.ToInt32(obj);
            if (SetUpType==1)
            {
                foreach (var item in config.AppSettings.Settings.AllKeys)
                {   if(item!= "Table")
                    if(!DataGuidList.Any(t=>t.DatabaseName==item))
                    DataGuidList.Add(new SetUpModel()
                    {
                        DatabaseName = item,
                        ConnectingString = config.AppSettings.Settings[item].Value
                    });
                }
                return;
            }
            if (SetUpType == 2)
            {
                //SetUpTableModel
               // foreach (var item in config.AppSettings.Settings.AllKeys)
               // {
                    if (!string.IsNullOrWhiteSpace(config.AppSettings.Settings["Table"].Value))
                            DataGuidTableList = Newtonsoft.Json.JsonConvert.DeserializeObject<System.Collections.ObjectModel.ObservableCollection<SetUpTableModel>>(config.AppSettings.Settings["Table"].Value);
                //}
            }
           if (SetUpType==3)
            {
                foreach (var item in DataGuidList)
                {
                    if (DataGuidList.Where(t => t.DatabaseName == item.DatabaseName).Count() > 1)
                    {
                        System.Windows.MessageBox.Show("数据库名称不允许重复");
                        return;
                    }
                }
                foreach (var item in DataGuidTableList)
                {
                    if (DataGuidTableList.Where(t => t.TableName == item.TableName).Count() > 1)
                    {
                        System.Windows.MessageBox.Show("查询名称不允许重复");
                        return;
                    }
                }
                var configList= config.AppSettings.Settings.AllKeys.ToList().Where(t=>t!= "Table");
                if (DataGuidList.Count != 0)
                    foreach (var item in DataGuidList)
                {
                    if (configList.Any(t=>t==item.DatabaseName))
                    {
                        if(config.AppSettings.Settings[item.DatabaseName].Value!= item.ConnectingString)
                        config.AppSettings.Settings[item.DatabaseName].Value = item.ConnectingString;
                    }
                    else
                    {
                        config.AppSettings.Settings.Add(item.DatabaseName,item.ConnectingString);
                        item.IsAvailable = false;
                    }
                }
                if(DataGuidTableList.Count!=0)
                config.AppSettings.Settings["Table"].Value =Newtonsoft.Json.JsonConvert.SerializeObject(DataGuidTableList);

                ConfigSave();
            }
        }
        private bool AddCanExecute()
        {
            switch (SetUpType)
            {
                case 1:
                    return true;
                case 2:
                    return true;
                default:
                    return false;
            }
        }
        private void AddDoExecute(object obj)
        {
            switch (SetUpType)
            {
                case 1:
                    DataGuidList.Add(new SetUpModel()
                    {
                        IsAvailable = true
                    });
                    break;
                case 2:
                    DataGuidTableList?.Add(new SetUpTableModel()
                    {
                        IsAvailable= true
                    });
                    break;
                default:                  
                    break;
            }
        }
        //删除配置文件
        private bool DeleteExecute()
        {
            return true;
        }

        private void DeleteExecute(object obj)
        {
            var selectdata = obj as SetUpModel;
            if(selectdata != null)
            {
                config.AppSettings.Settings.AllKeys.ToList().Where(t => t == selectdata.DatabaseName);
                config.AppSettings.Settings.Remove(selectdata.DatabaseName);
                ConfigSave();
                DataGuidList.Remove(selectdata);
            }
            else
            {
                var selectdata1 = obj as SetUpTableModel;
                if (selectdata1 != null)
                {
                    DataGuidTableList.Remove(selectdata1);
                    config.AppSettings.Settings["Table"].Value = Newtonsoft.Json.JsonConvert.SerializeObject(DataGuidTableList);
                    ConfigSave();   
                }
            }
        }
        #endregion
        #region 属性
        System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(new System.Configuration.ExeConfigurationFileMap()
        {
            ExeConfigFilename = AppDomain.CurrentDomain.BaseDirectory + @"Configuration\App.config"
        }, System.Configuration.ConfigurationUserLevel.None);
        /// <summary>
        /// 
        /// </summary>
        private System.Collections.ObjectModel.ObservableCollection<SetUpModel> DataGuidList_;//=new System.Collections.ObjectModel.ObservableCollection<SetUpModel>();

        public System.Collections.ObjectModel.ObservableCollection<SetUpModel> DataGuidList
        {
            get {
                if(DataGuidList_ == null)
                DataGuidList_ = new System.Collections.ObjectModel.ObservableCollection<SetUpModel>();
                return DataGuidList_; }
            set { DataGuidList_ = value;
               // SetProperty(ref DataGuidList_, DataGuidList);
            }
        }
        private System.Collections.ObjectModel.ObservableCollection<SetUpTableModel> DataGuidTableList_ = new System.Collections.ObjectModel.ObservableCollection<SetUpTableModel>();

        public System.Collections.ObjectModel.ObservableCollection<SetUpTableModel> DataGuidTableList
        {
            get { return DataGuidTableList_; }
            set
            {
                DataGuidTableList_ = value;
                SetProperty(ref DataGuidTableList_, DataGuidTableList);
            }
        }
        private int SetUpType_=0;

        public int SetUpType
        {
            get { return SetUpType_; }
            set { SetUpType_ = value;
                SetProperty(ref SetUpType_, SetUpType);
            }
        }

        #endregion
        private void ConfigSave()
        {
            config.Save(System.Configuration.ConfigurationSaveMode.Modified);
            System.Configuration.ConfigurationManager.RefreshSection("appSettings");
        }
    }
}
